package serv

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func AdminRoleIndexCtrl(c *gin.Context) {
	if c.Request.Method == "POST" {
		param := GetJsonData(c)
		var adminUserArr []map[string]any
		where := "1"

		if param["name"] != nil {
			where += " and name like '%%" + param["name"].(string) + "%%'"
		}
		if param["username"] != nil {
			where += " and username like '%%" + param["username"].(string) + "%%'"
		}

		dbEngine.Table("f_role").Select("id,name,pid,`description`,access,status").Where(where).Find(&adminUserArr)
		cnt, _ := dbEngine.Table("f_role").Where(where).Count()

		c.JSON(200, ApiList{
			Status: 200,
			Data: ApiDataListObj{
				Total:       cnt,
				PerPage:     0,
				CurrentPage: 0,
				LastPage:    0,
				Data:        adminUserArr,
			},
		})
	} else {
		c.HTML(http.StatusOK, "admin-role-index.html", nil)
	}
}

func AdminRoleGetUpdateInfoCtrl(c *gin.Context) {
	param := GetJsonData(c)
	id := param["id"]

	nodeArr := map[string]any{}
	dbEngine.Table("f_role").Where("id=?", id).Get(&nodeArr)

	c.JSON(200, map[string]any{"status": 200, "data": nodeArr})
}

func AdminRoleUpdateCtrl(c *gin.Context) {
	param := GetJsonData(c)
	if param["id"] == nil {
		dbEngine.Table("f_role").Insert(param)
		c.JSON(200, map[string]any{
			"status": 200,
			"msg":    "添加成功",
		})
	} else {
		dbEngine.Table("f_role").Where("id=?", param["id"]).Update(param)
		c.JSON(200, map[string]any{
			"status": 200,
			"msg":    "更新成功",
		})
	}
}

func AdminRoleDeleteCtrl(c *gin.Context) {
	param := GetJsonData(c)

	if param["id"] != nil {
		dbEngine.Table("f_role").Where("id in (?)", param["id"]).Delete()
		c.JSON(200, map[string]any{
			"status": 200,
			"msg":    "删除成功",
		})
	}
}
